import { observable, action, computed, toJS } from 'mobx';
import { WeaLocaleProvider} from 'ecCom';
import { message } from 'antd';
import {uniqueId} from 'lodash';
import API from '../apis/app';
import ExcelApi from '../apis/excel';
import pathApi from '../apis/cuspath';
import mode from '../apis/mode';
import page from '../apis/page';
import FileUploadStore from './FileUploadStore';
const getLabel = WeaLocaleProvider.getLabel;

export default class ExcelJoinCubeStore {
    
    @observable edcAppId = '';
    @observable edcAppName = '';
    @observable selectTab = '';
    @observable tabs = [];
    @observable datas = [];
    @observable nodeOptionsInfo = {};

    @observable record = {};
    @observable createModeVisible = false;
    @observable createLoading = false;
    @observable cubeAppId = '';
    @observable cubeAppName = '';
    @observable cubeModeName = '';
    @observable appParams = {
        superid: 1,
        appid: '',
        addtype: 'addchild',
        name: '',
        desc: '',
        superapp: 1,
        showorder: 0,
        icon: 'icon-coms-ModelingEngine',
        iconColor: '#fff',
        iconBg: '#96358a',
        isInitalModeAndForm: 0,
        fromEDC:1
      };
    @observable modeParams = {
    modeid: '',
    modename: '',
    modetype: 4,
    formid: 0,
    modetitle: '',
    isaddrightbyworkflow: '1',
    id: 0,
    empowmentType: '0,0',
    mode_layoutids: '',
    mode_iscustomorder: '',
    mode_categorytype: '',
    fromEDC: 1
    };

    @observable fileUploadStore = new FileUploadStore();
    @observable fileVisible = false;
    @observable categoryInfo = {};
    
    @observable modeTabs = [];
    @observable selectModeTab = '';
    @observable pageExpandId = '';

    @observable saveLoading = false;

	@action init = (app) => {
        this.edcAppId = app.id;
        this.edcAppName = app.name;
        if(!this.cubeAppId) this.cubeAppId = app.cubeAppId;
        if(!this.cubeAppName) this.cubeAppName = app.cubeAppName;
        ExcelApi.getExcelPages(this.edcAppId).then(action(pages=>{
            if(pages && pages.length>0){
                this.tabs=[];
                pages.map(page=>{this.tabs.push({id:page.id,name:page.name});});
                this.selectTab = this.tabs[0].id;
                this.initTable();
            }
        }))
    }

    @action initTable = () => {
        pathApi.getJoinCubeSetting({pageid:this.selectTab}).then(action(datas=>{
            this.nodeOptionsInfo={};
            datas.map((data)=>{
                data.isUsed = `${data.isUsed}`;
                data.formmodeId = `${data.formmodeId?data.formmodeId:''}`;
                this.getNodeInfo(data);
            })
            this.datas = datas;
        }));
    }
    
    @action save = () => {
        const params = [];
        let flag = true;
        this.datas.map(data=>{
            if(data.isUsed==='1'){
                if(!data.formmodeId || data.formmodeId===''){
                    this[`modeError${data.id}`].showError();
                    flag = false;
                }else{
                    if(!data.nodes || data.nodes===''){
                        this[`nodesError${data.id}`].showError();
                        flag = false;
                    }
                }
            }
            params.push({
                id:data.id,
                isUsed:data.isUsed,
                formId:data.formId,
                formmodeId:data.formmodeId,
                nodes:data.nodes
            });
        });
        if(flag) {
            this.saveLoading = true;
            pathApi.saveJoinCubeSetting({setting:JSON.stringify(params)} ).then(action(()=>{
                message.success(getLabel('528334','保存成功！') );  
                this.saveLoading = false;
                this.initTable();
            }))
        }
    }

    @action getNodeInfo = (data) => {
        if(this.nodeOptionsInfo[data.sheetid]){
            const info = this.nodeOptionsInfo[data.sheetid];
            data.nodeOptions.map(d=>{
                if(d.seleted){
                    info.map(i=>{
                        if(d.key===i.key){
                            i.seleted = d.seleted;
                        }
                    })
                }
            });
            this.nodeOptionsInfo[data.sheetid] = [...info]
        }else{
            this.nodeOptionsInfo[data.sheetid] = data.nodeOptions;
        }
    } 

    @action changTab = (e) => {
        this.selectTab = e.target.value;
        this.initTable();
    }

    @action changeDatas = (datas) => {
        this.datas = datas;
    }
    
    @action changeRow = (record) => {
        const { id,fromWhere,formmodeId,options,nodes,nodeOptions } = record;
        const datas = this.datas;
        if(fromWhere){
            this.nodeOptionsInfo[record.sheetid].map(op=>{
                if(op.seleted===record.id) op.seleted=undefined;
            })

            this.datas = [...datas.filter((d,i)=>d.id!==id)]
        }else{
            let cusIndex;
            datas.map((d,i)=>{
                if(d.id===id || d.fromWhere===id){
                    cusIndex = i;
                }
            })
            const [array1, array2] = this.splitArray(datas,cusIndex);
            const newId = uniqueId('edc_');
            this.datas =[...array1,
                {...record,id:newId,fromWhere:id,isUsed:'0',formmodeId:'',nodes:'',isSetCategory:false,
                nodeOptions:this.getNodeOptions({...record,id:newId})
                }
                ,...array2]
        }
    }

    @action splitArray = (array, index) => {
        const array1 = [];
        const array2 = []
        array.forEach((value, i) => {
            if (i > index) {
                array2.push(value);
            } else {
                array1.push(value);
            }
        });
        return [array1, array2];
    }

    @action changeMode = (value,record) => {
        this.datas.map(data=>{
            if(data.id===record.id) data.formmodeId = value;
        });
    }
        
    @action newCubeMode = (record) => {
        const {formId,pageid,sheetName} = record;
        this.record = record;
        this.createModeVisible = true;
        let excelName = '';
        this.tabs.map(tab=>{if(tab.id===pageid) excelName = tab.name});
        if(!this.cubeAppId) this.cubeAppName=`[数据中心]${this.edcAppName}`;
        this.cubeModeName = `[数据中心]${excelName}${sheetName}`
    }

    @action triggerFileSetting = (record) => {
        console.log("触发附件目录上传",record)
        const { formId,formmodeId } = record;
        this.fileUploadStore.setModeid(formmodeId);
        this.fileUploadStore.setFormid(formId);
        this.fileUploadStore.initFileUploadSet();
        this.fileUploadStore.getUploadFieldInfo();
        page.isSetCategory(formmodeId).then((data) => {
            //joinCube.isSetCategory = data.isSetCategory;
            //this.pageExpandId = data.pageExpandId;
            this.categoryInfo = data.categoryInfo;
            this.fileUploadStore.initNames({
              ...data.categoryInfo,
              modeId: formmodeId,
            });
            this.fileVisible = true;
        });
    }

    @action hideFileSetting = () => {
        this.fileVisible = false;
        if(this.fileUploadStore.fieldcount>0) this.initTable();
    }

    @action getNodeOptions = (record) => {
        if(this.nodeOptionsInfo){
            return this.nodeOptionsInfo[record.sheetid].filter(o=>!o.seleted || o.seleted===record.id);
        }
        return [];
    }

    @action changeNodes = (value,record) => {
        const valueStr = `,${value},`;
        this.nodeOptionsInfo[record.sheetid].map(op=>{
            if(op.seleted===record.id) op.seleted=undefined;
            if(valueStr.indexOf(`,${op.key},`)>-1) op.seleted = record.id;
        }) 

        this.datas.map(data=>{
            if(data.id===record.id){
                data.nodes = value;
            }
        });
    }

    @action hideCreateMode = () => {
        this.createModeVisible = false;
    }

    @action changeCubeAppName = (value) => {
        this.cubeAppName = value;
    }

    @action changeCubeModeName = (value) => {
        this.cubeModeName = value;
    }

    @action createMode = () => {
        if(this.cubeAppName==='') {
            message.error('应用名称为空！');
            return;
        }
        if(this.cubeModeName==='') {
            message.error('模块名称为空！');
            return;
        }
        this.createLoading = true;
        if(!this.cubeAppId){
            mode.saveApp({...this.appParams,name: this.cubeAppName,edcAppid:this.edcAppId}).then((res) => {
                this.cubeAppId = res.appid;
                this.updateEdcAppInfo();
                this.createModeByApp();
            });
        }else{
            this.createModeByApp();
        }
    }

    @action createModeByApp = () => {
        mode.saveMode({...this.modeParams,
            modetype: this.cubeAppId,
            modename: this.cubeModeName,
            modetitle: this.cubeModeName,
            formid: this.record.formId,
            edcAppid: this.edcAppId
        }).then((res) => {
            if (res.status == '1') {
                this.createLoading = false;
                this.createModeVisible = false;
                message.success(getLabel('528335','创建成功') );
                this.changeModeOptions(`${res.id}`);
                this.changeMode(`${res.id}`,this.record);
            }
        });
    }

    @action updateEdcAppInfo = () => {
        API.updateCubeAppIdToEdc({edcAppId:this.edcAppId,cubeAppId:this.cubeAppId});
    }

    @action changeModeOptions = (modeId) => {
        this.datas.map(d=>{
            if(d.formId===this.record.formId) d.options.push({key:modeId,showname:this.cubeModeName});
        })
    }

    @action getAppModeInfo = (app) => {//初始化应用所关联的模块
        API.getAppModeInfo({appId:app.id}).then(action((result)=>{
            this.modeTabs = result;
            if(this.modeTabs.length>0){
                this.selectModeTab = this.modeTabs[0].id;
                this.pageExpandId = this.modeTabs[0].newSavePageExpandId;
            }else{
                this.selectModeTab = '';
                this.pageExpandId = '';
            }
        }));
    }

    @action changModeTab = (e) => {
        this.selectModeTab = e.target.value;
        this.modeTabs.map(tab=>{
            if(tab.id===this.selectModeTab) this.pageExpandId = tab.newSavePageExpandId
        })
    }
}